var initAroundSearch;
var aroundGraphicLayer;
var bufferCircle = null;
var draw;
var aroundSearchParam = [];
var setAroundParams;
var center;

require([
    "dojo/on",
    "esri/symbols/SimpleMarkerSymbol",
    "esri/symbols/SimpleLineSymbol",
    "esri/symbols/SimpleFillSymbol",
    "esri/symbols/PictureMarkerSymbol",
    "esri/layers/GraphicsLayer",
    "esri/toolbars/draw",
    "esri/graphic",
    "esri/geometry/Point", "esri/geometry/Circle","esri/InfoTemplate",
    "dojo/domReady!"
], function (
    on, SimpleMarkerSymbol, SimpleLineSymbol, SimpleFillSymbol, PictureMarkerSymbol,
    GraphicsLayer, Draw, Graphic, Point, Circle,InfoTemplate) {

    initAroundSearch = function () {
        //反向地址搜索的图层
        aroundGraphicLayer = new GraphicsLayer({
            id: "aroundGraphicLayer"
        });
        map.addLayer(aroundGraphicLayer);

        draw = new Draw(map);
        //绑定绘图事件
        draw.on("draw-complete", addGraphicToMap);
    }

    function addGraphicToMap(evt) {
        draw.deactivate();
        aroundGraphicLayer.clear();
        map.setMapCursor("default");
        var radius = $('#aroundRadius').val();
        center = evt;
        if (bufferCircle !== null) {
            bufferCircle = new esri.geometry.Circle({
                center: evt,
                radius: radius
            });
        } else {
            center = evt.geometry;
            bufferCircle = new esri.geometry.Circle({
                center: evt.geometry,
                radius: radius
            });
        }

        var graphic = new Graphic(bufferCircle, highlightPolySymbol);
        aroundGraphicLayer.add(graphic);

        var sms = new PictureMarkerSymbol("img/marker/map-marker.png", 30, 30);
        var centerGraphic = new esri.Graphic(evt.geometry, sms, null, null);

        aroundGraphicLayer.add(centerGraphic);

        aroundSearchParam = [center.x, center.y, radius];

        map.infoWindow.clearFeatures();
        drawFlag = false;
    }

    setAroundParams = function (graphicArr) {
        selectedGraphicArr = graphicArr;
    }

    //选中要素右键的反向检索
    $("#doCtxAroundBtn").click(function () {
        var radius = parseFloat($("#gAroundInput").val());
        var centerPoint;

        aroundGraphicLayer.clear();

        if (selectedGraphicArr[0].geometry.type == "polygon") {
            centerPoint = selectedGraphicArr[0].geometry.getCentroid();
        } else if (selectedGraphicArr[0].geometry.type == "point") {
            centerPoint = selectedGraphicArr[0].geometry;
        }

        bufferCircle = new Circle({
            center: centerPoint,
            radius: radius
        });

        var graphic = new Graphic(bufferCircle, highlightPolySymbol);
        aroundGraphicLayer.add(graphic);

        var sms = new PictureMarkerSymbol("img/marker/map-marker.png", 30, 30);
        aroundGraphicLayer.add(new Graphic(centerPoint, sms));

        doAroundQuery(centerPoint);
    })

    function doAroundQuery(center) {
        aroundQueryList = [];
        var onBufferType = $("#gAroundType").val();
        var distance = $("#gAroundInput").val();
        thematicGraphicLayer.clear();

        $("#gAroundTab1 a").click();
        $("#gAroundList ul").empty();
        $("#gAroundList .waitPanel").show();

        aroundSearchParam = [center.x, center.y, distance];

        $.ajax({
            type: "POST",
            url: "RangeSearchServlet",
            dataType: "json",
            data: {
                x: center.x,
                y: center.y,
                type: onBufferType,
                distance: distance,
            },
            success: function (result) {
                aroundQueryList = result.result;
                $("#gAroundList .waitPanel").hide();
                $("#gAroundPage").initPage(aroundQueryList.length, 1, buildGAround);
            },
            error: function (result) {
                // var resultObj=eval('(' + result.responseText + ')');
                console.log(result.responseText);
                // var resultObj = JSON.parse(result.responseText);
                // aroundQueryList = resultObj.result;

                aroundQueryList = [];
                $("#gAroundList .waitPanel").hide();
                $("#gAroundPage").initPage(aroundQueryList.length, 1, buildGAround);
            }
        });

        function buildGAround(page) {
            $("#gAroundList>ul").empty();
            var sli = "<li><span class='data_count'>共有" + aroundQueryList.length + "个结果</span><button class='btn btn-success exportBtn' id='exportCSV1'>导出</button></li>"
            $("#gAroundList>ul").append(sli);
            thematicGraphicLayer.clear();
            map.removeLayer(thematicGraphicLayer);
            map.addLayer(thematicGraphicLayer)

            //绑定导出事件
            $("#exportCSV1").click(function () {
                exportAroundCSV(aroundQueryList);
            })

            var max = page * 10;

            if (max > aroundQueryList.length) {
                max = aroundQueryList.length
            }

            for (var i = (page - 1) * 10; i < max; i++) {
                var item = aroundQueryList[i];
                var sms = new PictureMarkerSymbol("img/marker/" + (i + 1 - (page - 1) * 10) + ".png", 30, 30);
                var pt = new Point(Number(item["point"]["X"]), Number(item["point"]["Y"]), map.spatialReference);
                var attr = {};
                var infoCont = "<div style='font-size:16px;font-weight:bold'>";

                // attr["name"] = item["attribute"][3]["value"];
                attr["名称"] = item["attribute"][3]["value"];
                attr["类型"] = item["attribute"][1]["value"] + "-" + item["attribute"][2]["value"];
                attr["距离"] = item["attribute"][0]["value"];
                //   infoCont+="名称"+": "+ attr["名称"]+" <br/>";
                infoCont += "类型" + ": " + attr["类型"] + " <br/>";
                infoCont += "距离" + ": " + attr["距离"] + " 米 <br/>";
                infoCont += "</div>"
                var infoTemplate = new esri.InfoTemplate("<b>" + attr["名称"] + "</b>", infoCont);
                var graphic = new esri.Graphic(pt, sms, attr, infoTemplate);

                thematicGraphicLayer.add(graphic);

                //第一个地址居中
                if (i === (page - 1) * 10) {
                    // map.centerAndZoom(pt,7);
                    map.setExtent(bufferCircle.getExtent(), true);
                    //map.centerAndZoom(new esri.geometry.Point(bufferPoint.x+300,bufferPoint.y+60,map.spatialReference),6);
                    map.centerAt(new esri.geometry.Point(bufferCircle.center.x + 0.6 * bufferCircle.radius, bufferCircle.center.y + 0.12 * bufferCircle.radius, map.spatialReference));
                    // dd.addClass('active');
                }

                thematicGraphicLayer.add(graphic);

                var li = document.createElement("li");
                var corp_name = document.createElement("p");
                corp_name.className = "corp_name";

                corp_name.innerHTML = "<img height='25px' src='img/marker/" + (i + 1 - (page - 1) * 10) + ".png'/>" + "&nbsp" + attr["名称"];
                // corp_name.innerHTML = "<i class=\"fa fa-map-marker\"></i>" + "&nbsp" + attr["名称"];
                var person_name = document.createElement("p");
                person_name.className = "person_name";
                person_name.innerHTML = attr["类型"];

                li.appendChild(corp_name);
                li.appendChild(person_name);

                $("#gAroundList>ul").append(li);

                (function (li, arg, idx, g) {
                    on(li, "click", function () {
                        $('#thematicQueryList a').removeClass('active');

                        // var center = new esri.geometry.Point(arg.x * 1 + 120, arg.y * 1, map.spatialReference);
                        map.infoWindow.hide();
                        map.infoWindow.setContent(g.getContent());
                        map.infoWindow.setTitle(g.getTitle());
                        map.infoWindow.show(g.geometry);
                        map.centerAndZoom(g.geometry, 6);

                    });
                })(li, pt, i, graphic);
            }
        }

    }


    //反向搜索工具
    $("#doAroundBtn").click(() => {
        doNearQuery(center);
    })

    function doNearQuery(center) {
        aroundQueryList = [];
        var onBufferType = $("#aroundType").val();
        var distance = $("#aroundRadius").val();
        thematicGraphicLayer.clear();

        $("#aroundTab1 a").click();

        $("#aroundList ul").empty();
        $("#aroundList .waitPanel").show();

        $.ajax({
            type: "GET",
            url: "RangeSearchServlet",
            dataType: "json",
            data: {
                x: center.x,
                y: center.y,
                type: onBufferType,
                distance: distance,
            },
            success: function (result) {
                aroundQueryList = result.result;
                $("#aroundList .waitPanel").hide();
                $("#aroundPage").initPage(aroundQueryList.length, 1, buildAround);
            },
            error: function (result) {
                aroundQueryList = [];
                // aroundQueryList = result.result;
                $("#aroundList .waitPanel").hide();
                $("#aroundPage").initPage(aroundQueryList.length, 1, buildAround);
            }
        });

        function buildAround(page) {
            $("#aroundList>ul").empty();
            var sli = "<li><span class='data_count'>共有" + aroundQueryList.length + "个结果</span><button class='btn btn-success exportBtn' id='exportCSV'>导出</button></li>"
            $("#aroundList>ul").append(sli);
            thematicGraphicLayer.clear();
            map.removeLayer(thematicGraphicLayer);
            map.addLayer(thematicGraphicLayer)

            $("#exportCSV").click(function () {
                exportAroundCSV(aroundQueryList);

            })

            var max = page * 10;

            if (max > aroundQueryList.length) {
                max = aroundQueryList.length
            }

            for (var i = (page - 1) * 10; i < max; i++) {
                var item = aroundQueryList[i];
                var sms = new PictureMarkerSymbol("img/marker/" + (i + 1 - (page - 1) * 10) + ".png", 30, 30);
                var pt = new Point(Number(item["point"]["X"]), Number(item["point"]["Y"]), map.spatialReference);
                var attr = {};
                var infoCont = "<div style='font-size:16px;font-weight:bold'>";

                // attr["name"] = item["attribute"][3]["value"];
                attr["名称"] = item["attribute"][3]["value"];
                attr["类型"] = item["attribute"][1]["value"] + "-" + item["attribute"][2]["value"];
                attr["距离"] = item["attribute"][0]["value"];
                //   infoCont+="名称"+": "+ attr["名称"]+" <br/>";
                infoCont += "类型" + ": " + attr["类型"] + " <br/>";
                infoCont += "距离" + ": " + attr["距离"] + " 米 <br/>";
                infoCont += "</div>"

                var infoTemplate = new esri.InfoTemplate("<b>" + attr["名称"] + "</b>", infoCont);
                var graphic = new esri.Graphic(pt, sms, attr, infoTemplate);

                thematicGraphicLayer.add(graphic);

                //第一个地址居中
                if (i === (page - 1) * 10) {
                    // map.centerAndZoom(pt,7);
                    map.setExtent(bufferCircle.getExtent(), true);
                    //map.centerAndZoom(new esri.geometry.Point(bufferPoint.x+300,bufferPoint.y+60,map.spatialReference),6);
                    map.centerAt(new esri.geometry.Point(bufferCircle.center.x + 0.6 * bufferCircle.radius, bufferCircle.center.y + 0.12 * bufferCircle.radius, map.spatialReference));
                    // dd.addClass('active');
                }

                thematicGraphicLayer.add(graphic);

                var li = document.createElement("li");
                var corp_name = document.createElement("p");
                corp_name.className = "corp_name";

                corp_name.innerHTML = "<img height='25px' src='img/marker/" + (i + 1 - (page - 1) * 10) + ".png'/>" + "&nbsp" + attr["名称"];
                // corp_name.innerHTML = "<i class=\"fa fa-map-marker\"></i>" + "&nbsp" + attr["名称"];
                var person_name = document.createElement("p");
                person_name.className = "person_name";
                person_name.innerHTML = attr["类型"];

                li.appendChild(corp_name);
                li.appendChild(person_name);

                $("#aroundList>ul").append(li);

                (function (li, arg, idx, g) {
                    on(li, "click", function () {
                        $('#thematicQueryList a').removeClass('active');

                        // var center = new esri.geometry.Point(arg.x * 1 + 120, arg.y * 1, map.spatialReference);
                        // map.centerAndZoom(center, 6);
                        map.infoWindow.hide();
                        map.infoWindow.setContent(g.getContent());
                        map.infoWindow.setTitle(g.getTitle());
                        map.infoWindow.show(g.geometry);
                        map.centerAndZoom(g.geometry, 6);

                    });
                })(li, pt, i, graphic);
            }
        }

    }

    //添加反向搜索中心点
    $("#addAroundPoint").click(function () {
        bufferCircle = null;
        drawFlag = true;
        menpai = true;
        aroundGraphicLayer.clear();
        map.setMapCursor("pointer");
        draw.activate(esri.toolbars.Draw.POINT);
        map.infoWindow.clearFeatures();
    });


    //复合检索
    $("#multiAroundSearchBtn").click(() => {
        var title0 = $("#multiAroundPanel").find(".file-caption-name")[0].title;

        if (title0 != "") {
            $("#multiAroundPanel").find(".fileinput-upload")[0].click();
        } else {
            warningAlert("请选择复合检索中心点文件");
        }
    })

    //复合检索文件解析结果
    $("#multiAround_iframeContent").on("load", function () {
        var responseText = $("#multiAround_iframeContent")[0].contentDocument.body.getElementsByTagName("pre")[0].innerHTML;

        const layerListType = "multiAroundLayerList";

        var fileNameWithExt;

        var index = responseText.lastIndexOf(".");
        var ext = responseText.substr(index + 1);

        if (responseText.substr(responseText.length - 1, 1) == "}") {
            if (responseText == '{}') {
                failAlert("您加载的excel无内容，请检查后重新上传！");
            } else {
                resultJSON = eval('(' + responseText + ')');
                fileNameWithExt = resultJSON.fileName + ".xls";
                localFileName = fileNameWithExt + "的复合检索结果";
            }
        } else if (ext == "csv") {
            fileNameWithExt = responseText;
            localFileName = fileNameWithExt + "的复合检索结果";
        }

        fileParse(responseText, layerListType);

        let radius = $("#multiAaroundRadius").val();
        let type = $("#multiAroundType").val();


        let aroundResult = [];
        matchGraphics = [];
        matchGeometries = [];

        let circleGraphics = [];

        selectedGeometryArr = selectedGraphicArr.map(item => {
            return item.geometry;
        })

        selectedGeometryArr.forEach((point) => {
            let x = point.x;
            let y = point.y;

            let multiAroundCircle = new esri.geometry.Circle({
                center: point,
                radius: radius
            });

            var graphic = new Graphic(multiAroundCircle, highlightPolySymbol, {});
            circleGraphics.push(graphic);

            aroundGraphicLayer.add(graphic);

            aroundResult.push(multiAroundSearch(x, y, radius, type));
        })
        var layerId = "localDataFeatureLayer" + (localDataFeatureLayers.length - 1);

        circleObj[layerId] = circleGraphics;

        Promise.all(aroundResult).then((values) => {
            values.map((v, index) => {
                if (v == "error") {
                    console.log("第" + (index + 1) + "个请求失败")
                } else {
                    console.log(v);
                }
            })

            setBufferParams(matchGraphics);

            createFeatureLayer(matchGraphics, fileNameWithExt + "的复合检索结果", layerListType);
            // $("#lcoalLayerList_" + (loaclDataGraphicsLayers.length + 1) + "_span").click();
        }).catch(e => {
            console.log("all error")
            console.log(e);
        });

    });

    let multiAroundSearch = function (x, y, radius, type) {

        const promise = new Promise((resolve) => {
            $.ajax({
                type: "GET",
                url: "RangeSearchServlet",
                dataType: "json",
                data: {
                    x: x,
                    y: y,
                    type: type,
                    distance: radius,
                },
                success: function (result) {
                    aroundQueryList = result.result;

                    for (var i = 0; i < aroundQueryList.length; i++) {
                        var item = aroundQueryList[i];
                        var sms = new PictureMarkerSymbol("img/marker/map-marker.png", 30, 30);
                        var pt = new Point(Number(item["point"]["X"]), Number(item["point"]["Y"]), map.spatialReference);
                        var attr = {};
                        var infoCont = "<div style='font-size:16px;font-weight:bold'>";

                        // attr["name"] = item["attribute"][3]["value"];
                        attr["检索中心点X坐标"] = x;
                        attr["检索中心点Y坐标"] = y;
                        attr["检索半径"] = radius;
                        attr["名称"] = item["attribute"][3]["value"];
                        attr["类型"] = item["attribute"][1]["value"] + "-" + item["attribute"][2]["value"];
                        attr["距离"] = item["attribute"][0]["value"];
                        attr["x"] = item["point"]["X"];
                        attr["y"] = item["point"]["Y"];

                        infoCont += "类型" + ": " + attr["类型"] + " <br/>";
                        infoCont += "距离" + ": " + attr["距离"] + " 米 <br/>";
                        infoCont += "</div>"

                        var infoTemplate = new esri.InfoTemplate("<b>" + attr["名称"] + "</b>", infoCont);
                        var graphic = new esri.Graphic(pt, sms, attr, infoTemplate);

                        if (attr == {}) {
                            console.log(graphic)
                        }

                        if (typeof (attr) == undefined) {
                            console.log(graphic)
                        }

                        matchGraphics.push(graphic);
                        matchGeometries.push(pt);

                    }

                    resolve();

                },
                error: function (result) {
                    aroundQueryList = [];
                    // aroundQueryList = result.result;
                    // $("#aroundList .waitPanel").hide();
                    // $("#aroundPage").initPage(aroundQueryList.length, 1, buildAround);
                }
            });
        })

        return promise;
    }


})


function exportAroundCSV(aroundQueryList) {
    let convertArrayOfObjectsToCSV = function (value) {
        var result, ctr, columnDelimiter, lineDelimiter, data;
        var keys = [];
        data = value.data || null;
        if (data == null || !data.length) {
            return null;
        }
        columnDelimiter = value.columnDelimiter || ',';
        lineDelimiter = value.lineDelimiter || '\n';
        keys = ["检索中心点X坐标", "检索中心点Y坐标", "检索半径", "距检索中心点距离", "类型", "子类型", "名称", "x", "y"];
        result = '';
        result += keys.join(columnDelimiter);
        result += lineDelimiter;
        // keys = ["Distance", "main_type", "sub_type", "name"];
        data.forEach((item, index) => {
            let attribute = item.attribute;
            let point = item.point;

            result += parseFloat(aroundSearchParam[0]).toFixed(2).toString();
            result += columnDelimiter;
            result += parseFloat(aroundSearchParam[1]).toFixed(2).toString();
            result += columnDelimiter;
            result += parseFloat(aroundSearchParam[2]).toFixed(2).toString();

            attribute.forEach((item) => {
                result += columnDelimiter;
                result += item["value"];
            });
            result += columnDelimiter;
            result += parseFloat(point["X"]).toFixed(2).toString();
            result += columnDelimiter;
            result += parseFloat(point["Y"]).toFixed(2).toString();
            result += lineDelimiter;

        });
        return result;
    };


    var data = aroundQueryList;
    var tableName = "反向地址检索结果";
    var csv = convertArrayOfObjectsToCSV({
        data: data
    });

    csv = "\ufeff" + csv;

    var blob = new Blob([csv], {
        type: "text/plain;charset=utf-8"
    });
    saveAs(blob, tableName + ".csv");
}